package com.epalmpay.service.app.impl;

import com.epalmpay.dto.appshop.ShopTradeStatisOutDTO;
import com.epalmpay.dto.appshop.TradeSendOutDTO;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.PayBalanceChange;
import com.epalmpay.service.app.IAppShopCollectionService;
import com.epalmpay.service.posapi.PosApiServiceTransactional;
import com.epalmpay.util.*;
import com.epalmpay.util.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/2/26.
 */
@Service("appShopCollectionService")
public class IAppShopCollectionServiceImpl implements IAppShopCollectionService{

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private TradeOfflineMapper tradeOfflineMapper;

    @Resource
    private StatisShopDayMapper statisShopDayMapper;

    @Resource
    private BonusSendLogMapper bonusSendLogMapper;

    @Resource
    private CouponMapper couponMapper;

    @Resource
    private CouponUserMapper couponUserMapper;

    @Resource
    private BonusVerifyLogMapper bonusVerifyLogMapper;

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private OrderServiceGoodDetailMapper orderServiceGoodDetailMapper;

    @Resource
    private ShopGroupRelationMapper shopGroupRelationMapper;

    @Resource
    private PosApiServiceTransactional posApiServiceTransactional;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private DeviceScanMapper deviceScanMapper;

    @Resource
    private DeviceDeskCardMapper deviceDeskCardMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private MemberGradeMapper memberGradeMapper;
    @Resource
    private OrderServiceGoodMapper orderServiceGoodMapper;

    @Resource
    private MallGoodMapper mallGoodMapper;

    @Value("${PROFIT_URL}")
    private String profiturl;


    @Override
    public Response isHas(String shopId) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Device device = deviceMapper.queryDeviceByShopId(Long.parseLong(shopId));
        if(device ==null){
         return  Response.getError("商户信息不存在");
        }

        if(device.getCashierModeDeskcard()!=null){
            map.put("cashierModeScan",device.getCashierModeScan());
        }else{
            map.put("cashierModeScan",false);
        }
        if(device.getCashierModeDeskcard()!=null){
            map.put("cashierModeDeskcard",device.getCashierModeDeskcard());
        }else{
            map.put("cashierModeDeskcard",false);
        }
        map.put("deviceStatus",device.getDeviceStatus());
        return Response.getSuccess(map);
    }

    @Override
    public Response memberData(String phone,String shopId,String tradeMoney) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Integer tradeAmount = Integer.parseInt(tradeMoney);

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(Long.parseLong(shopId));
        if(shopInfo == null || shopInfo.size() == 0) {
            return  Response.getError("商户信息不存在");
        }
        Long groupId = (Long) shopInfo.get("groupId");
        Date now = new Date();

        Member member = memberMapper.getMemberByCardNoOrPhone(Long.parseLong(shopId), phone); //查询用户信息
        if(member != null) {                   //已经存在则查询相关权益
            map.put("memberName", member.getName());
            map.put("memberCardNo", member.getCardNo());
            map.put("mobile", member.getPhone());
            map.put("icCardNo",member.getIccardNo());
            List<Map<String, Object>> userCoupons = couponUserMapper.listUserCouponsInfo(member.getId(), ActivityEnum.CouponUseStatus.Received.getType(),
                    tradeAmount, ActivityEnum.ActivityPlatformType.OffLine.getType(), null);
            if (userCoupons == null || userCoupons.size() == 0) {
                map.put("couponNum", 0);
                map.put("coupons", new ArrayList<Map>());
            } else {
                Iterator<Map<String, Object>> couponIterator = userCoupons.iterator();
                while (couponIterator.hasNext()) {
                    Map<String, Object> coupon = couponIterator.next();

                    //优惠券是否在有效期
                    if ((Integer) coupon.get("validTimeType") == ActivityEnum.ValidTimeType.FixedTime.getType()) {
                        if (now.compareTo((Date) coupon.get("validStartTime")) < 0 || now.compareTo((Date) coupon.get("validEndTime")) > 0) {
                            couponIterator.remove();
                            continue;
                        }
                    } else if ((Integer) coupon.get("validTimeType") == ActivityEnum.ValidTimeType.AfterGet.getType()) {
                        Integer days = (Integer) coupon.get("days");
                        Date validUseEnd = DateUtil.getDateNext((Date) coupon.get("getTime"), days);
                        if (now.compareTo(validUseEnd) > 0) {
                            couponIterator.remove();
                            continue;
                        }
                    } else { //其他有效日期类型无效
                        couponIterator.remove();
                        continue;
                    }

                    //优惠券在门店是否可用
                    String shopIdsStr = (String) coupon.get("shopIds");
                    String[] shopIds;
                    if (shopIdsStr == null) {
                        couponIterator.remove();
                        continue;
                    } else if (shopIdsStr.equals("-1")) {    //所有门店可用
                        continue;
                    } else {
                        shopIds = shopIdsStr.split(",");
                    }

                    boolean contains = false;
                    for (int j = 0; j < shopIds.length; j++) {
                        if (Long.parseLong(shopIds[j]) == Long.parseLong(shopId)) {
                            contains = true;
                            break;
                        }
                    }
                    if (!contains) {
                        couponIterator.remove();
                    }
                    coupon.remove("shopIds");   //移除门店信息
                }
                map.put("couponNum", userCoupons.size());
                map.put("coupons", userCoupons);
            }

            //积分
            Map<String, Integer> userCanVerifyBonus = posApiServiceTransactional.userCanVerifyBonus(Long.parseLong(shopId), groupId, member, now, tradeAmount);

            map.put("point", member.getBonusAmount());
            map.put("pointUseMax", userCanVerifyBonus.get("pointUseMax"));
            map.put("frequency_min", userCanVerifyBonus.get("frequency_min"));
            map.put("pointChangeRate", userCanVerifyBonus.get("verifyRate"));
            map.put("cantVerifyReason", userCanVerifyBonus.get("cantVerifyReason"));
            map.put("freePassword", true);
        }else {
            if(Tools.checkMobileNumber(phone)) {
                //创建用户信息
                Group group = groupMapper.selectByPrimaryKey(groupId);

         //       MemberGrade memberGrade = memberGradeMapper.selectMemberGradeByGroupIdAndGradeName(groupId, BizEnum.MemberGradeDefault.unattention.getName());
                
               //取值第2个会员等级id
  			   List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(groupId);

                Userbase userbase = new Userbase();
                userbase.setStatus(BizEnum.UserStatus.Normal.getType());
                userbase.setUserType(CommonEnum.UserType.User.getType());
                userbase.setGmtCreate(now);
                userbase.setGroupId(groupId);
                userbase.setUsername(phone);

                Member member1 = new Member();
                member1.setGroupId(groupId);
                member1.setPhone(phone);
                member1.setName(phone);
                member1.setFromType(BizEnum.MemberDevelopeFrom.ShopDevelope.getType());
                member1.setFromMode(BizEnum.MemberDevelopeMode.PosConsume.getType());
                member1.setFromId(Long.parseLong(shopId));
                member1.setFromName((String) shopInfo.get("shopName"));
                member1.setStatus(BizEnum.MemberStatus.unattention.getType());
                member1.setGmtCreate(now);
                member1.setWalletGmtCreate(now);
                member1.setWalletStatus(1);
                member1.setWxsubStaus(0);
//                if(memberGrade != null) {
//                    member1.setGradeId(memberGrade.getId());
//                }
                if(memberGradeList.size()>1){
                	//取值第二个会员等级
                	member1.setGradeId(memberGradeList.get(1).getId());
                }
                
                String password="888888";
                // String  password=mobile.substring(mobile.length()-6);
                member1.setTradePassword(AES.AESEncode(Const.AceKey, password));

                //会员卡号生成
                String virtualCardNO = "" + group.getPayGroupCode() + shopId + (new Date().getTime()+"").substring(0, 10);
                member1.setVirtualCard(virtualCardNO);
                member1.setCardNo("VIP" + DateUtil.getMonth()+Tools.getRandomNum(6));

                try {
                    posApiServiceTransactional.saveCreateMember(userbase, member1, group.getPayGroupCode());
                } catch (Exception e) {
                    e.printStackTrace();
                    return Response.getError("服务器处理错误");
                }

                map.put("mobile", phone);
                map.put("memberCardNo", member1.getCardNo());
                map.put("couponNum", 0);
                map.put("coupons", new ArrayList<Map>());

                //积分
                map.put("frequency_min", 0);
                map.put("pointUseMax", 0);
                map.put("point", 0);
                map.put("pointChangeRate", 0);

                map.put("freePassword", true);
            } else {
                return Response.getError("账户不存在");
            }
        }
//        else{
//            map.put("isMember", false);
//        }

        return Response.getSuccess(map);
    }

    @Override
    public Response collectImg(String shopId) throws ApplicationException {
        Map<String,Object> map = new HashMap<String,Object>();
//        Shop shop = shopMapper.selectByPrimaryKey(Long.parseLong(shopId));
        Shop shop = shopMapper.getShopCollectionInfo(Long.parseLong(shopId));
        if (shop ==null) {
            return Response.getError("商户信息不存在");
        }
        map.put("shopName",shop.getMerchantName());
        if(shop.getQrcodePath() !=null){
            map.put("url",shop.getQrcodePath());
        }else{
            return Response.getError("台卡信息不存在");
        }

        return Response.getSuccess(map);
    }

    @Override
    public Response shopCollectionInfo(String shopId) throws ApplicationException {
        Map<String,Object> map = new HashMap<String,Object>();
        Device device = deviceMapper.queryshopCollectionInfo(Long.parseLong(shopId));
        if(device ==null){
            return Response.getError("收银设备信息不存在");

        }
        map.put("shopName",device.getShopName());
        map.put("deviceName",device.getDeviceName());

        DeviceScan deviceScan = deviceScanMapper.selectByDeviceId(device.getId());
        if(deviceScan !=null){
            map.put("scanMerchantName",deviceScan.getScanMerchantName());
            map.put("scanMerchantId",deviceScan.getScanMerchantId());
            map.put("scanOrganization",deviceScan.getScanOrganization());
            map.put("scanFeeRate",deviceScan.getFeeRate());
            map.put("scanTerminalId",deviceScan.getScanTerminalId());
        }
        DeviceDeskCard deviceDeskCard = deviceDeskCardMapper.selectByDeviceId(device.getId());
        if(deviceDeskCard !=null){
            map.put("deskMerchantName",deviceDeskCard.getDeskcardMerchantName());
            map.put("deskMerchantId",deviceDeskCard.getDeskcardMemMerchantCode());
            map.put("deskOrganization",deviceDeskCard.getDeskcardOrganization());
            map.put("deskFeeRate",deviceDeskCard.getFeeRate());
            map.put("deskTerminalId",null);
        }
        return Response.getSuccess(map);
    }

    @Override
    public Response collectionRecord(String shopId, String joinTime, String endTime, Integer collectType) throws ApplicationException {
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        if(joinTime ==null){
            param.put("joinTime", new Date());
        }else{
            param.put("joinTime", joinTime);
        }
        if(endTime !=null){
            param.put("endTime", endTime);
        }
        if(collectType !=null){
            param.put("collectType", collectType);
        }
        param.put("shopId", Long.parseLong(shopId));

        TradeOffline tradeOffline = tradeOfflineMapper.queryShopCollectionData(param);
        if(tradeOffline !=null){
            map.put("totalCount",tradeOffline.getTotalCount());
            map.put("realAmount",tradeOffline.getRealAmount());
        }

        return Response.getSuccess(map);
    }



    @Override
    public Response tradeList(String shopId, String startDate,String endDate, Integer payType,Integer transactionType, Integer pageNo, Integer pageSize) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> shopTradeList = new ArrayList<Map<String, Object>>();

        Map<String, Object> param = new HashMap<String, Object>();
        if (payType !=null) {
            param.put("payType", payType);
        }
        if (transactionType !=null) {
            param.put("transactionType", transactionType);
        }
        param.put("shopId", Long.parseLong(shopId));

        if (startDate !=null) {
            param.put("statisDate", startDate);
        }else{
            param.put("statisDate", new Date());
        }
        if (endDate !=null) {
            param.put("endDate", endDate);
        }

        TradeOffline result = tradeOfflineMapper.queryTradeShopData(param);
        map.put("number",result.getNumber());
        map.put("factAmount",result.getRealAmount());

        //首次点击交易记录
        if(transactionType==null && payType==null){
            TradeOffline result2 = tradeOfflineMapper.queryRefund(param);
            map.put("refundNumber",result2.getNumber());
            map.put("refundFactAmount",result2.getRealAmount());
        }else{
            map.put("refundNumber",0);
            map.put("refundFactAmount",0);
        }


        int count = tradeOfflineMapper.queryShopTradeCount(param);
        if (count == 0) {
            map.put("shopTradeList", shopTradeList);
            return Response.getSuccess(map);
        }

        param.put("start", pageSize * (pageNo - 1));
        param.put("limit", pageSize);

        List<TradeOffline> tradeOfflineList = tradeOfflineMapper.queryShopTradeList(param);

        for (TradeOffline tradeOffline : tradeOfflineList) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("id", tradeOffline.getId());
            detail.put("gmtCreate", tradeOffline.getGmtCreate());
            if(tradeOffline.getPayerName() !=null){
                detail.put("memberName", tradeOffline.getPayerName());
            }else{
                detail.put("memberName", "");
            }
            if(tradeOffline.getPayerId() !=null){
                detail.put("memberId", tradeOffline.getPayerId());
            }else{
                detail.put("memberId",0);
            }
            detail.put("orderAmount", tradeOffline.getRealAmount());
            if(tradeOffline.getPayType() !=null){
                detail.put("payType",BizEnum.PaymentType.fromType(tradeOffline.getPayType()).getName());
            }else{
                detail.put("payType","");
            }
            shopTradeList.add(detail);
        }
        map.put("shopTradeList", shopTradeList);

        return Response.getSuccess(map);
    }

    @Override
    public Response entityGoodTradeList(String shopId, String startDate, String endDate, Integer payType, Integer transactionType, Integer pageNo, Integer pageSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> shopTradeList = new ArrayList<Map<String, Object>>();

        Map<String, Object> param = new HashMap<String, Object>();
        if (payType !=null) {
            param.put("payType", payType);
        }
        if (transactionType !=null) {
            param.put("transactionType", transactionType);
        }
        param.put("shopId", Long.parseLong(shopId));

        if (startDate !=null) {
            param.put("statisDate", startDate);
        }else{
            param.put("statisDate", new Date());
        }
        if (endDate !=null) {
            param.put("endDate", endDate);
        }

        TradeOffline result = tradeOfflineMapper.queryEntityGoodTradeShopData(param);
        map.put("number",result.getNumber());
        map.put("factAmount",result.getRealAmount());
        map.put("settingPrice",result.getSettingPrice());
        map.put("amount",result.getOrderAmount());

//        //首次点击交易记录 退款的
//        if(transactionType==null && payType==null){
//            TradeOffline result2 = tradeOfflineMapper.queryRefund(param);
//            map.put("refundNumber",result2.getNumber());
//            map.put("refundFactAmount",result2.getRealAmount());
//        }else{
//            map.put("refundNumber",0);
//            map.put("refundFactAmount",0);
//        }


        int count = tradeOfflineMapper.queryEntityGoodShopTradeCount(param);
        if (count == 0) {
            map.put("shopTradeList", shopTradeList);
            return Response.getSuccess(map);
        }

        param.put("start", pageSize * (pageNo - 1));
        param.put("limit", pageSize);

        List<TradeOffline> tradeOfflineList = tradeOfflineMapper.queryEntityGoodShopTradeList(param);

        for (TradeOffline tradeOffline : tradeOfflineList) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("id", tradeOffline.getId());
            detail.put("gmtCreate", tradeOffline.getGmtCreate());
            if(tradeOffline.getPayerName() !=null){
                detail.put("memberName", tradeOffline.getPayerName());
            }else{
                detail.put("memberName", "");
            }
            if(tradeOffline.getPayerId() !=null){
                detail.put("memberId", tradeOffline.getPayerId());
            }else{
                detail.put("memberId",0);
            }
            detail.put("orderAmount", tradeOffline.getRealAmount());
            detail.put("payType",BizEnum.PaymentType.fromType(tradeOffline.getPayType()).getName());
            shopTradeList.add(detail);
        }
        map.put("shopTradeList", shopTradeList);

        return Response.getSuccess(map);
    }

    @Override
    public Response tradeDetail(String tradeId,String shopId,String memberId) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();

        TradeOffline tradeOffline = tradeOfflineMapper.findTradeDetail(Long.parseLong(tradeId),Long.parseLong(shopId),memberId);
        map.put("transactionStatus",BizEnum.TransactionStatus.fromType(tradeOffline.getTransactionStatus()).getName());
        map.put("transactionType",BizEnum.TransactionType.fromType(tradeOffline.getTransactionType()).getName());
        map.put("payType",BizEnum.PaymentType.fromType(tradeOffline.getPayType()).getName());
        if(tradeOffline.getPayerName()!=null){
            map.put("payerName",tradeOffline.getPayerName());
        }else{
            map.put("payerName","");
        }
        if(tradeOffline.getCardNo() !=null){
            map.put("cardNo",tradeOffline.getCardNo());
        }else{
            map.put("cardNo","");
        }
        map.put("gmtCreate",tradeOffline.getGmtCreate());
        map.put("orderId",tradeOffline.getOrderId());
        map.put("orderAmount",tradeOffline.getOrderAmount());
        map.put("discountAmount",tradeOffline.getDiscountAmount());
        map.put("realAmount",tradeOffline.getRealAmount());
        map.put("bonusValue",tradeOffline.getBonusValue());
        map.put("bonusAmount",tradeOffline.getBonusAmount());
        //抵扣金额为0 时候 是没有优惠券名称的
        if(tradeOffline.getName() !=null){
            map.put("couponName",tradeOffline.getName());
        }else{
            map.put("couponName","");
        }
        if(tradeOffline.getRedpackageName() !=null){
            map.put("redpackageName",tradeOffline.getRedpackageName());
        }else{
            map.put("redpackageName","");
        }
        map.put("customerCount",tradeOffline.getTotalCount());

//        TradeSendOutDTO tradeSendOutDTO = tradeOfflineMapper.selectSendBonusData(Long.parseLong(tradeId),Long.parseLong(shopId));

        List<TradeSendOutDTO> tradeSendOutDTOList =tradeOfflineMapper.selectSendBonusData(Long.parseLong(tradeId),Long.parseLong(shopId));

        TradeOffline tradeOffline1 = tradeOfflineMapper.getTradeDataByRelatedTradeOfflineId(Long.parseLong(tradeId),memberId);
        if(tradeOffline1 !=null){
            map.put("cash", tradeOffline1.getRealAmount());
        }else{
            map.put("cash", 0);
        }

        String sendCouponName="";
        int sendCouponAmount=0;
        for(TradeSendOutDTO tradeSendOutDTO :tradeSendOutDTOList) {
            if (tradeSendOutDTO != null) {
                map.put("sendBonus", tradeSendOutDTO.getSendBonusAmount());
                if (tradeSendOutDTO.getCouponName() != null) {
                    sendCouponName +=tradeSendOutDTO.getCouponName()+",";
                } else {
//                    map.put("sendCouponName", "");
                }
                sendCouponAmount +=tradeSendOutDTO.getSendCouponAmount();

            }
        }
        map.put("sendCouponAmount", sendCouponAmount);
        if(sendCouponName !=null && !sendCouponName.equals("")){
            map.put("sendCouponName", sendCouponName.substring(0,sendCouponName.length()-1));
        }else{
            map.put("sendCouponName", "");
        }

        return Response.getSuccess(map);
    }

    @Override
    public Response shopTradeStatisData(String shopId,String statisDate) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shopId", Long.parseLong(shopId));
        if (statisDate !=null) {
            param.put("statisDate", statisDate);
            map.put("statisDate", statisDate);
        }else{
            param.put("statisDate", new Date());
            String dateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
            map.put("statisDate", dateStr);

        }
        ShopTradeStatisOutDTO shopTradeStatisOutDTO = tradeOfflineMapper.shopTradeStatisData(param);
        if(shopTradeStatisOutDTO ==null){
            return Response.getError("商户信息不存在");
        }
        map.put("totalNumber",shopTradeStatisOutDTO.getTotalNumber());
        map.put("totalAmount",shopTradeStatisOutDTO.getTotalAmount());
        map.put("totalRealAmount",shopTradeStatisOutDTO.getTotalRealAmount());
        map.put("totalCouponNumber",shopTradeStatisOutDTO.getTotalCouponNumber());
        map.put("totalCouponAmount",shopTradeStatisOutDTO.getTotalCouponAmount());
        map.put("totalSendCouponNumber",shopTradeStatisOutDTO.getTotalSendCouponNumber());
        map.put("totalBonusCount",shopTradeStatisOutDTO.getTotalBonusCount());
        map.put("totalBonusNumber",shopTradeStatisOutDTO.getTotalBonusNumber());
        map.put("totalBonusAmount",shopTradeStatisOutDTO.getTotalBonusAmount());
        map.put("totalSendBonusCount",shopTradeStatisOutDTO.getTotalSendBonusCount());
        map.put("totalSendBonusNumber",shopTradeStatisOutDTO.getTotalSendBonusNumber());
        map.put("totalMemberNumber",shopTradeStatisOutDTO.getTotalMemberNumber());
        map.put("totalMemberAmount",shopTradeStatisOutDTO.getTotalMemberAmount());
        map.put("noMemberCustomerCount",shopTradeStatisOutDTO.getNoMemberCustomerCount());
        map.put("noMemberCustomerAmount",shopTradeStatisOutDTO.getNoMemberCustomerAmount());
        map.put("newMemberCount",shopTradeStatisOutDTO.getNewMemberCount());
        map.put("oldMemberCount",shopTradeStatisOutDTO.getOldMemberCount());
        map.put("addMemberCount",shopTradeStatisOutDTO.getAddMemberCount());
        map.put("totalVeriftyCouponCount",shopTradeStatisOutDTO.getTotalVeriftyCouponCount());
        map.put("totalVeriftyAmount",shopTradeStatisOutDTO.getTotalVeriftyAmount());
        map.put("totalSettingPriceAmount",shopTradeStatisOutDTO.getTotalSettingPriceAmount());
        map.put("entntyGoodNumber",shopTradeStatisOutDTO.getEntntyGoodNumber());
        map.put("entntyGoodRealAmount",shopTradeStatisOutDTO.getEntntyGoodRealAmount());
        map.put("entntyGoodSettingAmount",shopTradeStatisOutDTO.getEntntyGoodSettingAmount());


        return Response.getSuccess(map);
    }

    @Override
    public Response collectionDetail(String shopId, String statisDate) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shopId", Long.parseLong(shopId));
        param.put("statisDate", statisDate);

        TradeOffline  tradeOffline = tradeOfflineMapper.collectionDetail(param);
        if(tradeOffline ==null){
            return Response.getError("商户信息不存在");
        }
        map.put("totalNumber",tradeOffline.getTotalCount());
        map.put("totalAmount",tradeOffline.getOrderAmount());
        map.put("totalRealAmount",tradeOffline.getRealAmount());

        List<ShopTradeStatisOutDTO> shopTradeStatisOutDTOList =tradeOfflineMapper.selectShopTradeDetailList(param);

        List<Map<String, Object>> shopTradeList = new ArrayList<Map<String, Object>>();
        for (ShopTradeStatisOutDTO shopTradeStatisOutDTO : shopTradeStatisOutDTOList) {
            Map<String, Object> detail = new HashMap<String, Object>();
            //查询不同的支付方式使用优惠抵扣券张数
            ShopTradeStatisOutDTO  res = tradeOfflineMapper.queryCouponCount(Long.parseLong(shopId),statisDate,shopTradeStatisOutDTO.getPayType());
            detail.put("totalCouponNumber", res.getTotalCouponNumber());
            detail.put("payType", shopTradeStatisOutDTO.getPayType());
            detail.put("number", shopTradeStatisOutDTO.getTotalNumber());
            detail.put("realAmount", shopTradeStatisOutDTO.getTotalRealAmount());
            detail.put("totalCouponAmount", shopTradeStatisOutDTO.getTotalCouponAmount());
            detail.put("totalBonusNumber", shopTradeStatisOutDTO.getTotalBonusNumber());
            detail.put("totalBonusAmount", shopTradeStatisOutDTO.getTotalBonusAmount());
            shopTradeList.add(detail);
        }
        if (shopTradeList.size() > 0) {
            map.put("shopTradeList", shopTradeList);
        }

        return Response.getSuccess(map);
    }

    @Override
    public Response customerMemberDetail(String shopId, String statisDate) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shopId", Long.parseLong(shopId));
        param.put("statisDate", statisDate);

        TradeOffline  tradeOffline = tradeOfflineMapper.customerMemberDetail(param);
        if(tradeOffline ==null){
            return Response.getError("商户信息不存在");
        }
        map.put("totalMemberNumber",tradeOffline.getTotalCount());
        map.put("totalCustomerAmount",tradeOffline.getRealAmount());

        List<ShopTradeStatisOutDTO> shopTradeStatisOutDTOList =tradeOfflineMapper.selectCustomerMemberDetail(param);

        List<Map<String, Object>> shopTradeMemberList = new ArrayList<Map<String, Object>>();



        //构造24小时数据
        int hours = 24;
        int tmpLeng = shopTradeStatisOutDTOList.size();
        int count = 0;
        int tmpHour = 0;
        ArrayList <ShopTradeStatisOutDTO> newList = new ArrayList<ShopTradeStatisOutDTO>();
        ShopTradeStatisOutDTO statisticResult = null;
        for(int i=0;i<24;i++){
            String str="";
            if(i<10){
                str += 0+String.valueOf(i);
            }
            else{
                str += String.valueOf(i);
            }
            if(count<tmpLeng){
                tmpHour = Integer.parseInt(shopTradeStatisOutDTOList.get(count).getHourString());
                if(i==tmpHour){
                    statisticResult= statisticResult.getShopTradeMemberDataList(str,shopTradeStatisOutDTOList.get(count).getNewMemberCount(),shopTradeStatisOutDTOList.get(count).getOldMemberCount());
                    newList.add(shopTradeStatisOutDTOList.get(count));
                    count++;
                }else{
                    statisticResult= statisticResult.getShopTradeMemberDataList(str,0,0);
                    newList.add(statisticResult);
                }
            }else{
                statisticResult= statisticResult.getShopTradeMemberDataList(str,0,0);
                newList.add(statisticResult);
            }
        }




            for (ShopTradeStatisOutDTO shopTradeStatisOutDTO : newList) {
                Map<String, Object> detail = new HashMap<String, Object>();

                    detail.put("hourString,", shopTradeStatisOutDTO.getHourString()+":00");

                    if(shopTradeStatisOutDTO.getGmtCreate() !=null){
                        param.put("gmtCreate",shopTradeStatisOutDTO.getGmtCreate());//具体那一天的那个小时 查询新会员老会员消费金额
                    }else{
                        param.put("gmtCreate",statisDate+" "+shopTradeStatisOutDTO.getHourString());//具具体那一天的那个小时 查询新会员老会员消费金额
                    }


    //                detail.put("hourString,", shopTradeStatisOutDTO.getHourString());
                    detail.put("newMemberCount", shopTradeStatisOutDTO.getNewMemberCount());
                    detail.put("oldMemberCount", shopTradeStatisOutDTO.getOldMemberCount());
                    //查询新会员老会员消费金额
    //                param.put("gmtCreate", shopTradeStatisOutDTO.getGmtCreate());//集体那一天的那个小时

                    ShopTradeStatisOutDTO resNew = tradeOfflineMapper.queryNewCustomerAmount(param);//新会员这天这个小时消费金额 新(今天)
                    detail.put("newMemberAmount", resNew.getNewMemberAmount());
                    ShopTradeStatisOutDTO resOld = tradeOfflineMapper.queryOldCustomerAmount(param);//新会员这天这个小时消费金额 新(今天)
                    detail.put("oldMemberAmount", resOld.getOldMemberAmount());

                    shopTradeMemberList.add(detail);
            }
            if (shopTradeMemberList.size() > 0) {
                map.put("shopTradeMemberList", shopTradeMemberList);
            }


        return Response.getSuccess(map);
    }

    @Override
    public Response couponDataDetail(String shopId, String statisDate,Integer pageNo,Integer pageSize) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shopId", Long.parseLong(shopId));
        param.put("statisDate", statisDate);

        ShopTradeStatisOutDTO  rest =tradeOfflineMapper.selectCouponDataDetail(param);
        if(rest ==null){
            return Response.getError("商户信息不存在");
        }
        map.put("totalCouponAmount",rest.getTotalCouponAmount());//优惠券抵扣金额
        map.put("totalCouponNumber",rest.getTotalCouponNumber());//优惠券发放笔数
        map.put("totalSendCouponNumber",rest.getTotalSendCouponNumber());//优惠券发放张数
        map.put("totalCouponCount",rest.getTotalCouponCount());//优惠券抵扣张数

        //查询各种优惠券发放的张数
        List<Coupon> couponList = couponMapper.queryCouponDataList(param);
        List<Map<String, Object>> eachCouponList = new ArrayList<Map<String, Object>>();
        for (Coupon coupon : couponList) {
            Map<String, Object> detail = new HashMap<String, Object>();

            detail.put("couponName", coupon.getName());
            detail.put("totalCount", coupon.getTotalCount());
            eachCouponList.add(detail);
        }
        if (eachCouponList.size() > 0) {
            map.put("eachCouponList", eachCouponList);
        }

        List<ShopTradeStatisOutDTO> shopTradeStatisOutDTOList =couponMapper.selectCouponDataList(param);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();


        //构造24小时数据
        int hours = 24;
        int tmpLeng = shopTradeStatisOutDTOList.size();
        int count = 0;
        int tmpHour = 0;
        ArrayList <ShopTradeStatisOutDTO> newList = new ArrayList<ShopTradeStatisOutDTO>();
        ShopTradeStatisOutDTO statisticResult = null;
        for(int i=0;i<24;i++){
            String str="";
            if(i<10){
                str += 0+String.valueOf(i);
            }
            else{
                str += String.valueOf(i);
            }
            if(count<tmpLeng){
                tmpHour = Integer.parseInt(shopTradeStatisOutDTOList.get(count).getHourString());
                if(i==tmpHour){
                    statisticResult= statisticResult.getShopTradeList(str,shopTradeStatisOutDTOList.get(count).getTotalSendCouponNumber());
//                    statisticResult= statisticResult.getNewMemberList(String.valueOf(i),hourMemberList.get(count).getAddUserCount());
                    newList.add(shopTradeStatisOutDTOList.get(count));
                    count++;
                }else{
                    statisticResult= statisticResult.getShopTradeList(str,0);
                    newList.add(statisticResult);
                }
            }else{
                statisticResult= statisticResult.getShopTradeList(str,0);
                newList.add(statisticResult);
            }
        }



        for (ShopTradeStatisOutDTO shopTradeStatisOutDTO : newList) {
            Map<String, Object> detail2 = new HashMap<String, Object>();

                detail2.put("hourString,", shopTradeStatisOutDTO.getHourString()+":00");
                detail2.put("totalSendCouponNumber", shopTradeStatisOutDTO.getTotalSendCouponNumber());

            if(shopTradeStatisOutDTO.getGmtCreate() !=null){
                param.put("gmtCreate",shopTradeStatisOutDTO.getGmtCreate());//具体那一天的那个小时 去查核销张数笔数
            }else{
                param.put("gmtCreate",statisDate+" "+shopTradeStatisOutDTO.getHourString());//具体那一天的那个小时 去查核销张数笔数
            }

            CouponUser couponUser =  couponUserMapper.selectVeriftyCount(param);
            if(couponUser !=null){
                detail2.put("couponVerifyCount", couponUser.getCount());
            }else{
                detail2.put("couponVerifyCount", 0);
            }
            //抵扣金额
            TradeOffline tradeOffline = tradeOfflineMapper.selectEveryHourDisCountAmount(param);
            if(tradeOffline !=null){
                detail2.put("discountAmount", tradeOffline.getDiscountAmount());
            }else{
                detail2.put("discountAmount", 0);
            }
            list.add(detail2);



           /* for (ShopTradeStatisOutDTO shopTradeStatisOutDTO : shopTradeStatisOutDTOList) {
              Map<String, Object> detail2 = new HashMap<String, Object>();

//            detail2.put("hourString,", shopTradeStatisOutDTO.getHourString());
//            detail2.put("totalSendCouponNumber", shopTradeStatisOutDTO.getTotalSendCouponNumber());
//
//            param.put("gmtCreate",shopTradeStatisOutDTO.getGmtCreate());//具体那一天的那个小时 核销张数
           /* CouponUser couponUser =  couponUserMapper.selectVeriftyCount(param);
            if(couponUser !=null){
                detail2.put("couponVerifyCount", couponUser.getCount());
            }else{
                detail2.put("couponVerifyCount", 0);
            }
            //抵扣金额
            TradeOffline tradeOffline = tradeOfflineMapper.selectEveryHourDisCountAmount(param);
            if(tradeOffline !=null){
                detail2.put("discountAmount", tradeOffline.getDiscountAmount());
            }else{
                detail2.put("discountAmount", 0);
            }
            list.add(detail2);*/
        }
        if (list.size() > 0) {
            map.put("list", list);
        }

        return Response.getSuccess(map);
    }

    @Override
    public Response bonusDataDetail(String shopId, String statisDate, Integer pageNo, Integer pageSize) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shopId", Long.parseLong(shopId));
        param.put("statisDate", statisDate);

        //积分抵扣金额 积分抵扣点数
        TradeOffline tradeOffline = tradeOfflineMapper.queryVerifyBonusAmountAndCount(param);
        if(tradeOffline == null){
            return Response.getError("商户信息不存在");
        }
        map.put("totalBonusNumber",tradeOffline.getBonusAmount());//积分抵扣点数
        map.put("totalBonusAmount",tradeOffline.getBonusValue());//积分抵扣金额
        map.put("totalBonusCount",tradeOffline.getTotalCount());//积分抵扣笔数
        //积分发放点数 笔数
        BonusSendLog bonusSendLog = bonusSendLogMapper.selectBonusSendCountAndNum(param);
        map.put("bonusSendCount",bonusSendLog.getSendCount());//积分发放笔数
        map.put("totalSendBonusNumber",bonusSendLog.getAdjustAmount());//积分发放点数


        List<BonusSendLog> bonusSendLogList =bonusSendLogMapper.selectBonusDataList(param);
        List<Map<String, Object>> bonusList = new ArrayList<Map<String, Object>>();


        //构建24小时数据
        int hours = 24;
        int tmpLeng = bonusSendLogList.size();
        int count = 0;
        int tmpHour = 0;
        ArrayList <BonusSendLog> newList = new ArrayList<BonusSendLog>();
        BonusSendLog statisticResult = null;
        for(int i=0;i<24;i++){
            String str="";
            if(i<10){
                str += 0+String.valueOf(i);
            }
            else{
                str += String.valueOf(i);
            }
            if(count<tmpLeng){
                tmpHour = Integer.parseInt(bonusSendLogList.get(count).getHourString());
                if(i==tmpHour){
                    statisticResult= statisticResult.getNewBonusSendLogList(str,bonusSendLogList.get(count).getSendCount(),bonusSendLogList.get(count).getAdjustAmount());
//                    statisticResult= statisticResult.getNewMemberList(String.valueOf(i),hourMemberList.get(count).getAddUserCount());
                    newList.add(bonusSendLogList.get(count));
                    count++;
                }else{
                    statisticResult= statisticResult.getNewBonusSendLogList(str,0,0);
                    newList.add(statisticResult);
                }
            }else{
                statisticResult= statisticResult.getNewBonusSendLogList(str,0,0);
                newList.add(statisticResult);
            }
        }


        for (BonusSendLog bonus : newList) {
                Map<String, Object> detail = new HashMap<String, Object>();
                    detail.put("hourString,", bonus.getHourString()+":00");
                    detail.put("sendCount", bonus.getSendCount());
                    detail.put("sendbonusNumber", bonus.getAdjustAmount());
                    if(bonus.getGmtCreate() !=null){
                        param.put("gmtCreate",bonus.getGmtCreate());//具体那一天的那个小时 去查核销张数笔数
                    }else{
                        param.put("gmtCreate",statisDate+" "+bonus.getHourString());//具体那一天的那个小时 去查核销张数笔数
                    }

                BonusVerifyLog bonusVerifyLog =  bonusVerifyLogMapper.selectVeriftydata(param);
                if(bonusVerifyLog !=null){
                    detail.put("verifyCount", bonusVerifyLog.getVerifyCount());
                    detail.put("verifyBonusNumber",bonusVerifyLog.getAdjustAmount());
                }else{
                    detail.put("verifyCount", 0);
                    detail.put("verifyBonusNumber",0);
                }
                bonusList.add(detail);

        }

        if (bonusList.size() > 0) {
            map.put("bonusList", bonusList);
        }


        return Response.getSuccess(map);
    }

    @Override
    public Response addMemberDataDetail(String shopId, String statisDate, Integer pageNo, Integer pageSize) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shopId", Long.parseLong(shopId));
        param.put("statisDate", statisDate);
        Member member = memberMapper.queryAddMemberDataCount(param);
        map.put("addMemberTotalCount",member.getAddUserCount());

        List<Member> memberList = memberMapper.selectAddMemberCountByFromType(param);
        List<Map<String, Object>> memberModeList = new ArrayList<Map<String, Object>>();
        for(Member m :memberList){
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("fromName",m.getFromName());
            detail.put("addMemberCount",m.getAddUserCount());

            memberModeList.add(detail);
        }
        if (memberModeList.size() > 0) {
            map.put("memberModeList", memberModeList);
        }


        List<Member> hourMemberList =memberMapper.selectHourMemberCount(param);

        //构建24小时数据
        int hours = 24;
        int tmpLeng = hourMemberList.size();
        int count = 0;
        int tmpHour = 0;
        ArrayList <Member> newList = new ArrayList<Member>();
        Member statisticResult = null;
        for(int i=0;i<24;i++){
            String str="";
            if(i<10){
                str += 0+String.valueOf(i);
            }
            else{
                str += String.valueOf(i);
            }
            if(count<tmpLeng){
                tmpHour = Integer.parseInt(hourMemberList.get(count).getHourString());
                if(i==tmpHour){
                    statisticResult= statisticResult.getNewMemberList(str,hourMemberList.get(count).getAddUserCount());
//                    statisticResult= statisticResult.getNewMemberList(String.valueOf(i),hourMemberList.get(count).getAddUserCount());
                    newList.add(hourMemberList.get(count));
                    count++;
                }else{
                    statisticResult= statisticResult.getNewMemberList(str,0);
                    newList.add(statisticResult);
                }
            }else{
                statisticResult= statisticResult.getNewMemberList(str,0);
                newList.add(statisticResult);
            }
        }


        List<Map<String, Object>> memberHourModeList = new ArrayList<Map<String, Object>>();
        for(Member mem :newList){
            Map<String, Object> detailHour = new HashMap<String, Object>();
            detailHour.put("hourString",mem.getHourString()+":00");
            detailHour.put("memberCount",mem.getAddUserCount());
            memberHourModeList.add(detailHour);
        }
        if (memberHourModeList.size() > 0) {
            map.put("memberHourModeList", memberHourModeList);
        }
/*
        List<Map<String, Object>> memberHourModeList = new ArrayList<Map<String, Object>>();
        for(Member mem :hourMemberList){
            Map<String, Object> detailHour = new HashMap<String, Object>();
            detailHour.put("hourString",mem.getHourString()+":00");
            detailHour.put("memberCount",mem.getAddUserCount());
            memberHourModeList.add(detailHour);
        }
        if (memberHourModeList.size() > 0) {
            map.put("memberHourModeList", memberHourModeList);
        }
*/


        return Response.getSuccess(map);
    }

    @Override
    public Response couponCodeVerifyDetail(String shopId, String statisDate) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shopId", Long.parseLong(shopId));
        param.put("statisDate", statisDate);
        OrderServiceGoodDetail orderServiceGoodDetail = orderServiceGoodDetailMapper.queryCouponCodeVerifyData(param);
        if(orderServiceGoodDetail !=null){
           map.put("totalVerifyCount",orderServiceGoodDetail.getCount());
           map.put("totalVerifyAmount",orderServiceGoodDetail.getPrice());
        }
        List<OrderServiceGoodDetail> orderServiceGoodDetailList =orderServiceGoodDetailMapper.queryOrderServiceGoodDetailList(param);
        List<Map<String, Object>> verifyList = new ArrayList<Map<String, Object>>();
        for(OrderServiceGoodDetail res :orderServiceGoodDetailList){
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("goodName",res.getGoodName());
            detail.put("price",res.getPrice());
            detail.put("originalPrice",res.getOriginalPrice());
            detail.put("verifyCount",res.getCount());
            detail.put("verifyAmount",res.getVerifyAmount());

            verifyList.add(detail);
        }
        if (verifyList.size() > 0) {
            map.put("verifyList", verifyList);
        }


        return Response.getSuccess(map);
    }


    @Override
    public Response appCouponInfo(String sid, String couponCode) throws ApplicationException {


        Long shopId = Long.parseLong(sid);
        Map<String, Object> map = new HashMap<>();


        //对门票的处理 订单号 包含TICK的不按门店走
        OrderServiceGoodDetail orderServiceGoodDetail = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNo(couponCode);

        if(orderServiceGoodDetail==null){
            return Response.getError("券码未识别");
        }

        map =  orderServiceGoodDetailMapper.getCouponInfo(shopId + "", couponCode);
        if(map != null) {
            ActivityEnum.CouponCodeStatus[] couponCodeStatuses = ActivityEnum.CouponCodeStatus.values();
            Integer  a = Integer.parseInt(map.get("oldAmount").toString()==null ? "0" :map.get("oldAmount").toString());
            Integer  b = Integer.parseInt(map.get("payAmount").toString()==null ? "0" :map.get("payAmount").toString());
            map.put("payAmount", a);
            map.put("oldAmount", b);
            map.put("isCorrect",map.get("isCorrect"));
            for(int i = 0; i < couponCodeStatuses.length; i++) {
                if(couponCodeStatuses[i].getType() == (Integer)map.get("status")) {
                    map.put("statusName", couponCodeStatuses[i].getName());
                    break;
                }
            }
        } else {
            map = new HashMap<>();
            return Response.getError("券码未识别");
        }


        return Response.getSuccess(map);
    }

    @Override
    public Response appCouponVerify(String sid, String couponCode) throws ApplicationException, ParseException {
        Map<String, Object> map = new HashMap<>();
        Date date = new Date();
        Long shopId = Long.parseLong(sid);

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");


        String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();





        //门票逻辑
        OrderServiceGoodDetail orderServiceGoodDetail =new OrderServiceGoodDetail();
        orderServiceGoodDetail = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNo(couponCode);
        if(orderServiceGoodDetail ==null){
            return Response.getError("券码不存在");
        }


        orderServiceGoodDetail = orderServiceGoodDetailMapper.selectByCouponCode(couponCode, groupId, shopId);
        if (orderServiceGoodDetail == null) {
            return Response.getError("券码已失效(已被核销过)");
        }


        String[] shopIds = orderServiceGoodDetail.getCanUsedShop().split(",");

        for(int i = 0; i < shopIds.length; i++) {
            if(Long.parseLong(shopIds[i]) == shopId) {
                break;
            }

            if(i == shopIds.length - 1) {
                return Response.getError("当前门店不可核销");
            }
        }

        String beginTime = DateUtil.fomatDate(new Date(), DateUtil.sdfDay);
        String  endTime = DateUtil.fomatDate(orderServiceGoodDetail.getValidDate(), DateUtil.sdfDay);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date bt = sdf.parse(beginTime);
        Date et=sdf.parse(endTime);
        if(et.before(bt)) {
            return Response.getError("已过了可核销时间");
        }

        OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());
        short usedNumber = orderServiceGood.getUsedNumber() == null ? 0 : orderServiceGood.getUsedNumber();


        if(Integer.valueOf(usedNumber + 1).shortValue()== orderServiceGood.getNumber()) {
            orderServiceGood.setAllVerifyTime(date);
            orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForComment.getType());
//                orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.Verified.getType());
            orderServiceGood.setUsedNumber(orderServiceGood.getNumber());
        }else{
            orderServiceGood.setUsedNumber(Integer.valueOf(usedNumber + 1).shortValue());
        }


        //     MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());

        //券码详情记录更新
        orderServiceGoodDetail.setCouponStatus(ActivityEnum.CouponCodeStatus.Verified.getType());
        orderServiceGoodDetail.setVerifyTime(date);
        orderServiceGoodDetail.setShopId(shopId);
//        orderServiceGoodDetail.setPosId((Long) posInfo.get("deviceId"));
//        orderServiceGoodDetail.setPosName((String) posInfo.get("posName"));
        orderServiceGoodDetail.setGmtModified(date);

        PayBalanceChange payBalanceChange = null;
        TradeOffline tradeOffline = null;
//        if(mallGood.getWalletSettleMode() == 0) { //如果结算位置是门店
//            logger.debug(">>>>>>>>结算位置门店，进行打款计算");
//            Integer settingPrice = new BigDecimal(orderServiceGoodDetail.getOriginalPrice()).multiply(new BigDecimal(mallGood.getSettlementRate()))
//                    .divide(new BigDecimal(10000), 2,BigDecimal.ROUND_FLOOR).intValue();
//            orderServiceGoodDetail.setSettingPrice(settingPrice);
//
//            //支付平台请求对象创建
//            payBalanceChange = PayBalanceChange.initialize(payGroupCode, (String) shopInfo.get("payMerchantCode"), orderServiceGoodDetail.getSettingPrice().toString(),
//                    "1", UtilFun.createOrderNum(), DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");
//
//            Member member = memberMapper.selectByPrimaryKey(orderServiceGoodDetail.getMemberId());
//
//            //交易记录创建
//            tradeOffline = new TradeOffline();
//            tradeOffline.setGmtCreate(new Date());
//            tradeOffline.setGroupId(orderServiceGood.getGroupId());
//            tradeOffline.setOrderId(orderNo);
//            tradeOffline.setPayerId(member.getId());
//            tradeOffline.setPayerName(member.getName());
//            tradeOffline.setPayType((byte) CommonEnum.UserType.User.getType());
//            tradeOffline.setReceiverId(orderServiceGoodDetail.getShopId().toString());
//            tradeOffline.setReceiverName((String) shopInfo.get("shopName"));
//            tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
//            tradeOffline.setTransactionType((byte) BizEnum.TransactionType.CouponVerify.getType());
//            tradeOffline.setOrderAmount(orderServiceGoodDetail.getSettingPrice());
//            tradeOffline.setRealAmount(orderServiceGoodDetail.getSettingPrice());
//            tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
//            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
//            tradeOffline.setTransOrderNo(payBalanceChange.getOrgOrderNum());
//            tradeOffline.setMemo("券码核销打款到商户");
//        }
        try {
            posApiServiceTransactional.saveDoCouponVerify(orderServiceGood, orderServiceGoodDetail, payBalanceChange, tradeOffline);

            //获取供货价和实付金额
            String orderno = orderServiceGood.getOrderNo();
            TradeOffline to = tradeOfflineMapper.selectOfflineByTradeNo(orderno);
            int realamount = to.getRealAmount();
            MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());

            if(mallGood.getSupplyPrice() != null && realamount-mallGood.getSupplyPrice() > 0) {//只有分润金额大于0时才进行分润
                //进行分润计算
                Map param = new HashMap();
                param.put("groupid", groupId + "");
                param.put("profileamount", (realamount - mallGood.getSupplyPrice()) + "");
                param.put("orderno", orderno);
                //调用分润接口
                HttpClientUtil.post(profiturl + "group/profile/computeServiceProfile", param);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.getError("服务器处理错误");
        }

        return Response.getSuccess(map);
    }

    @Override
    public Response appCouponRefund(String sid, String couponCode) throws ApplicationException, ParseException {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(Long.parseLong(sid));
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Date dateAllowRefundTime = DateUtil.getAfterMinute(new Date(), -30);

        if(Tools.isEmpty(couponCode)) {
            return null;
        }

        //门票逻辑
        OrderServiceGoodDetail  orderServiceGoodDetail2 = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNoData(couponCode,(Long) shopInfo.get("groupId"));
        if(orderServiceGoodDetail2==null){
            return Response.getError("券码信息不存在");
        }
        //判断该券时候核销  未核销 不去冲正
        if(orderServiceGoodDetail2.getCouponStatus() ==2){
            int i = 0;
            if (orderServiceGoodDetail2.getOrderNo().contains("TICK")) {
                i = orderServiceGoodDetailMapper.updateRefundCoupon(null, couponCode, dateAllowRefundTime);
            } else {
                i = orderServiceGoodDetailMapper.updateRefundCoupon(Long.parseLong(sid), couponCode, dateAllowRefundTime);
            }
            if (i == 1) {
                //门票逻辑
                OrderServiceGoodDetail orderServiceGoodDetail = new OrderServiceGoodDetail();

                //正常逻辑
                orderServiceGoodDetail = orderServiceGoodDetailMapper.selectByCouponCode(couponCode, (Long) shopInfo.get("groupId"), (Long) shopInfo.get("shopId"));
                if(orderServiceGoodDetail==null){
                    return Response.getError("券码信息不存在");
                }
                OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());
                orderServiceGood.setUsedNumber((short) (orderServiceGood.getUsedNumber() - 1));
                orderServiceGood.setAllVerifyTime(null);
                orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForUse.getType());
                orderServiceGoodMapper.updateByPrimaryKeySelective(orderServiceGood);

                return Response.getSuccess(map);
            } else {
                return Response.getError("已超过可冲正时间或者券码已经冲正过一次");
            }
        }else {
            return Response.getError("该券码未核销,请先去核销");
        }

    }

    @Override
    public Response testCouponList(String shopId, String startDate, String endDate, Integer pageNo, Integer pageSize) throws ApplicationException {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> param = new HashMap<String, Object>();

        List<Map<String,Object>> testCouponList= new ArrayList<>();
        param.put("shopId",shopId);
        if(startDate !=null){
            param.put("startDate",startDate);
        }else{
            param.put("startDate",new Date());
        }
        if(endDate !=null){
            param.put("endDate",endDate);
        }
        OrderServiceGoodDetail result =orderServiceGoodDetailMapper.queryOrderServiceGoodDetail(param);
        if(result !=null){
            map.put("verifyCount",result.getCount());
            map.put("totalAmount",result.getPrice().toString());
            map.put("settingAmount",result.getSettingPrice().toString());
        }


        int count = orderServiceGoodDetailMapper.queryTestCouponCount(param);
        if(count ==0){
            map.put("testCouponList", testCouponList);
            return Response.getSuccess(map);
        }
        param.put("start", pageSize * (pageNo - 1));
        param.put("limit", pageSize);
        List<OrderServiceGoodDetail> orderServiceGoodDetailList =orderServiceGoodDetailMapper.queryTestCouponList(param);
        for(OrderServiceGoodDetail orderServiceGoodDetail :orderServiceGoodDetailList){
            Map<String, Object> dateil = new HashMap<String, Object>();
            dateil.put("id",orderServiceGoodDetail.getId());
            dateil.put("memberId",orderServiceGoodDetail.getMemberId());
            dateil.put("couponCode",orderServiceGoodDetail.getCouponCode());
            dateil.put("gmtCreate",orderServiceGoodDetail.getGmtCreate());
            if(orderServiceGoodDetail.getMemberName()!=null){
                dateil.put("memberName",orderServiceGoodDetail.getMemberName());
            }else{
                dateil.put("memberName","");
            }
            dateil.put("price",orderServiceGoodDetail.getPrice().toString());
            testCouponList.add(dateil);
        }

        if(testCouponList.size()>0){
            map.put("testCouponList",testCouponList);
        }
        return Response.getSuccess(map);
    }

    @Override
    public Response testCouponDetail(String id,String shopId,String memberId) throws ApplicationException {
        Map<String, Object> map = new HashMap<>();
        OrderServiceGoodDetail orderServiceGoodDetail =orderServiceGoodDetailMapper.queryCouponVerifyOrderServiceGoodDetail(Long.parseLong(id),Long.parseLong(shopId),Long.parseLong(memberId));

        if(orderServiceGoodDetail ==null){
            return Response.getError("核销详情不存在");
        }
        map.put("price",orderServiceGoodDetail.getPrice());
        map.put("couponStatus",ActivityEnum.CouponCodeStatus.fromType(orderServiceGoodDetail.getCouponStatus()).getName());
        map.put("goodName",orderServiceGoodDetail.getGoodName());
        map.put("memberName",orderServiceGoodDetail.getMemberName());
        map.put("cardNo",orderServiceGoodDetail.getCardNo());
        map.put("count",orderServiceGoodDetail.getCount());
        map.put("verifyTime",orderServiceGoodDetail.getVerifyTime());
        map.put("orderNo",orderServiceGoodDetail.getOrderNo());
        map.put("realAmount",orderServiceGoodDetail.getPrice());
        map.put("discountAmount",orderServiceGoodDetail.getDiscountAmount()/orderServiceGoodDetail.getNumber());
        map.put("settingPrice",orderServiceGoodDetail.getSettingPrice());
        map.put("couponCode",orderServiceGoodDetail.getCouponCode());

        return Response.getSuccess(map);
    }



}
